
const db = require('db');
const { getTokenInof } = require('tools/token');
const isLeader = require('tools/isLeader');
const log = require('tools/log');
const { toLimit, toSorterStin, toWhereStin } = require('tools/sqlString');

module.exports = async ctx => {
    const { connection, run } = db.init();
    try {
        ctx.status = 200;
        ctx.body = {
            list: await queryEntry(ctx, run),
            pagination: await pagination(ctx, run)
        };
    } catch (error) {
        log(error)
        log('---------------------------------------------------')
        ctx.status = 500;
        ctx.body = error;
    }
    connection.end();
}

async function queryEntry(ctx, run) {
    const body = ctx.request.body;
    const sqlStr = `
    SELECT * 
    FROM settlement 
    WHERE (1=1)
    ${permission(ctx)}
    ${toWhereStin(body.column, body.filters)}
    ${toSorterStin(body.sorter, `ORDER BY createTime DESC`)}
    ${toLimit(body.pagination)}
    `

    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return result.rows;
}

async function pagination(ctx, run) {
    const body = ctx.request.body;
    const sqlStr = `
    SELECT COUNT(*) as total
    FROM settlement 
    WHERE (1=1)
    ${permission(ctx)}
    ${toWhereStin(body.column, body.filters)}
    `

    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return {
        ...body.pagination,
        total: result.rows[0].total
    };
}

/** 数据权限 */
function permission(ctx) {
    const userInfo = getTokenInof(ctx.header.authorization).userInfo;
    const isL = isLeader(userInfo);
    
    if (isL) return '';

    return `AND (settlement.commercialSpecialistId=${userInfo.userid})`
}